package com.shopping.auth.listener;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.shopping.common.entity.vo.SendSmsParamVo;
import com.shopping.common.utils.TelSmsUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 消息队列监听者
 */
@Component
@Log4j2
public class RabbitMqListener {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 初始化队列
     * @return
     */
    @Bean
    public Queue initQueue(){
        return new Queue("send_sms",true);
    }

    /**
     * 监听队列
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "send_sms")
    public void  sendSms(String msg, Message message, Channel channel) {
        log.info("msg->【{}】",msg);
        // 消息唯一标识tag
        MessageProperties messageProperties = message.getMessageProperties();
        try {
            SendSmsParamVo sendSmsParamVo = JSONObject.parseObject(msg, SendSmsParamVo.class);

            // 此消息的唯一消息键
            String msgId = (String) redisTemplate.opsForValue().get("sms_msgId:" + sendSmsParamVo.getMsgId());
            // 已消费
            if(StringUtils.isNotEmpty(msgId)) {
                // 确认签收，不重回队列
                channel.basicAck(messageProperties.getDeliveryTag(),false);
                System.out.println("1");
                return;
            }

            // 生成验证码
            String code = RandomUtil.randomNumbers(6);
            // 未消费
            HashMap<String, String> map = new HashMap<>();
            map.put(sendSmsParamVo.getPhone(),code);
            // 发送验证码
            TelSmsUtils.sendSms(sendSmsParamVo.getPhone(),"code",map);
            // redis存储验证码
            redisTemplate.opsForValue().set("tel_code:"+sendSmsParamVo.getPhone(),code,15, TimeUnit.MINUTES);
            // 确认签收，不重回队列
            channel.basicAck(messageProperties.getDeliveryTag(),false);
            redisTemplate.opsForValue().set("sms_msgId:"+sendSmsParamVo.getMsgId(),sendSmsParamVo.getMsgId());
        } catch (IOException e) {
            try {
                // 确认没签收，重回队列
                channel.basicAck(messageProperties.getDeliveryTag(),false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }

    }

}
